<?php
namespace app\admin\controller\house;

use app\admin\controller\Common;
use app\admin\model\HouseProperty as PropertyModel;
use app\admin\model\HouseNumber as NumberModel;
use app\admin\model\HouseTenant as TenantModel;
use app\admin\model\HouseBilling as BillingModel;
use app\admin\model\BillSum as SumModel;
use app\admin\library\Property;
use app\admin\library\Date;
use think\db as Db;

class Uncollected extends Common
{
    public function index()
    {
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $properties = PropertyModel::where('admin_user_id', $loginUser['id'])->all();
        $this->assign('properties', $properties);
        $this->assign('house_property_id', $house_property_id);
        return $this->fetch();
    }

    //主页面 table查询
    public function query()
    {
        $page = $this->request->param('page/d', LAYUI_PAGE);
        $limit = $this->request->param('limit/d', LAYUI_LIMIT);
        $order = $this->request->param('order/s', '', 'trim');
        $field = $this->request->param('field/s', '', 'trim');
        if (!$order) {
            $field = 'a.start_time';
            $order = 'asc';
        }
        $loginUser = $this->auth->getLoginUser();
        $house_property_id = $this->request->param('house_property_id/d', Property::getProperty($loginUser['id']));
        $meter_reading_time = $this->request->param('meter_reading_time/s', '', 'trim');
        $conditions = array(
            ['a.house_property_id', '=', $house_property_id],
            ['a.start_time', '< time', 'today+10 days'],
            ['a.accounting_date', 'null', ''],
        );
        if ($meter_reading_time) {
            \array_push($conditions, ['a.meter_reading_time', '=', $meter_reading_time]);
        }
        $count = BillingModel::where($conditions)
        ->alias('a')
        ->count();
        $datas = BillingModel::where($conditions)
        ->alias('a')
        ->join('HouseNumber b', 'b.house_property_id = a.house_property_id and b.id = a.house_number_id')
        ->join('HouseProperty c', 'c.id = a.house_property_id')
        ->field('a.*, b.name, c.name as property_name')
        ->order($field, $order)
        ->page($page, $limit)
        ->select();
        foreach ($datas as $value) {
            $value['meter_reading_time'] = \substr($value['meter_reading_time'], 0, 10);
            $value['start_time'] = \substr($value['start_time'], 0, 10);
        }
        return $this->returnLayui($datas, $count);
    }

    //抄表
    public function edit()
    {
        $id = $this->request->param('id/d', 0);
        if (!$data = BillingModel::get($id)) {
            $this->error('记录不存在。');
        }
        $number_data = NumberModel::where('house_property_id', $data->house_property_id)
            ->where('id', $data->house_number_id)
            ->find();
        $data['house_number_name'] = $number_data->name;
        $property_name = PropertyModel::get($data->house_property_id);
        $data['house_property_name'] = $property_name->name;
        $this->assign('data', $data);
        return $this->fetch();
    }

    //抄表页面 保存
    public function save()
    {
        $id = $this->request->post('id/d', 0);
        $data = [
            'house_property_id' => $this->request->post('house_property_id/d', 0),
            'house_number_id' => $this->request->post('house_number_id/d', 0),
            'meter_reading_time' => $this->request->post('meter_reading_time/s', '', 'trim'),
            'electricity_meter_this_month' => $this->request->post('electricity_meter_this_month/d', 0),
            'water_meter_this_month' => $this->request->post('water_meter_this_month/d', 0),
            'electricity_meter_last_month' => $this->request->post('electricity_meter_last_month/d', 0),
            'water_meter_last_month' => $this->request->post('water_meter_last_month/d', 0),
            'rental' => $this->request->post('rental/d', 0),
            'deposit' => $this->request->post('deposit/d', 0),
            'garbage_fee' => $this->request->post('garbage_fee/d', 0),
            'other_charges' => $this->request->post('other_charges/f', 0),
            'note' => $this->request->post('note/s', '', 'trim'),
        ];
        if (!$billing_data = BillingModel::get($id)) {
            $this->error('记录不存在。');
        }
        $number_data = NumberModel::where('house_property_id', $billing_data->house_property_id)
        ->where('id', $billing_data->house_number_id)
        ->find();
        $data['electricity_consumption'] = $data['electricity_meter_this_month'] - $data['electricity_meter_last_month'];
        $data['electricity'] = $data['electricity_consumption'] * $number_data->electricity_price;
        $data['water_consumption'] = $data['water_meter_this_month'] - $data['water_meter_last_month'];
        $data['water'] = $data['water_consumption'] * $number_data->water_price;
        $data['total_money'] = intval($data['water'] + $data['electricity'] + $data['rental'] + $data['deposit']
            + $data['garbage_fee'] + $data['other_charges']);
        $billing_data->save($data);
        $this->success('修改成功');
    }

    public function print()
    {
        $id = $this->request->param('id/d', 0);
        $number_id = $this->request->param('number_id/d', 0);
        $number_data = NumberModel::get($number_id);
        $this->assign('rent_mark', $number_data->rent_mark);
        $this->assign('id', $id);
        $this->assign('number_id', $number_id);
        $this->assign('property_id', $number_data->house_property_id);
        $this->assign('tenant_id', $number_data->tenant_id);
        return $this->fetch();
    }

    //grid++ report 报表查询
    public function queryData()
    {
        $id = $this->request->param('id/d', 0);
        if (!$billing_data = BillingModel::get($id)) {
            $this->error('记录不存在。');
        }
        $number_data = NumberModel::get($billing_data->house_number_id);
        $property_data = PropertyModel::get($billing_data->house_property_id);
        $data = [
            "Table" => [
                [
                    "number_id" => $property_data->name . '-' . $number_data->name,
                    "start_time" => substr($billing_data->start_time, 0, 10),
                    "end_time" => substr($billing_data->end_time, 0, 10),
                    "electricity_meter_this_month" => $billing_data->electricity_meter_this_month,
                    "electricity_meter_last_month" => $billing_data->electricity_meter_last_month,
                    "electricity_consumption" => $billing_data->electricity_consumption,
                    "electricity_price" => $number_data->electricity_price,
                    "electricity" => $billing_data->electricity,
                    "meter_reading_time" => substr($billing_data->meter_reading_time, 0, 10),
                    "water_meter_this_month" => $billing_data->water_meter_this_month,
                    "water_meter_last_month" => $billing_data->water_meter_last_month,
                    "water_consumption" => $billing_data->water_consumption,
                    "water_price" => $number_data->water_price,
                    "water" => $billing_data->water,
                    "rental" => $billing_data->rental,
                    "deposit" => $billing_data->deposit,
                    "garbage_fee" => $billing_data->garbage_fee,
                    "other_charges" => $billing_data->other_charges,
                    "total_money" => $billing_data->total_money,
                    "note" => $billing_data->note,
                ]
            ]
        ];
        return json($data);
    }

    //到账
    public function account()
    {
        $id = $this->request->param('id/d', 0);
        if (!$billing_data = BillingModel::get($id)) {
            $this->error('记录不存在。');
        }
        $number_data = NumberModel::get($billing_data->house_number_id);
        $transFlag = true;
        Db::startTrans();
        try {
            if ($number_data->rent_mark === 'Y') {
                $billing_update['accounting_date'] = date('Y-m-d', time());
                $billing_data->save($billing_update);
                if ($billing_data->end_time) {
                    $dates = Date::getLease($number_data->checkin_time, $number_data->lease);
                    $billing_insert = [
                        'house_property_id' => $billing_data['house_property_id'],
                        'house_number_id' => $billing_data['house_number_id'],
                        'start_time' => $dates[0],
                        'end_time' => $dates[1],
                        'tenant_id' => $number_data['tenant_id'],
                        'rental' => $number_data['rental'],
                        'garbage_fee' => $number_data['garbage_fee'],
                        'electricity_meter_last_month' => $billing_data['electricity_meter_this_month'],
                        'water_meter_last_month' => $billing_data['water_meter_this_month'],
                        'total_money' => $number_data['rental'],
                    ];
                    $new_billing = BillingModel::create($billing_insert);
                    $number_update['payment_time'] = $billing_insert['start_time'];
                    $number_update['receipt_number'] = $new_billing['id'];
                    $number_update['lease'] = $number_data['lease'] + 1;
                    $number_data->save($number_update);
                }
            } else {
                //退房清算
                $billing_update['accounting_date'] = date('Y-m-d', time());
                $billing_data->save($billing_update);
                $number_update = [
                    'payment_time' => null,
                    'receipt_number' => '',
                ];
                $number_data->save($number_update);
            }
            //总表记录
            $sum_data = [
                'house_property_id' => $billing_data['house_property_id'],
                'house_number_id' => $billing_data['house_number_id'],
                'type' => TYPE_RENT,
                'total_money' => $billing_data['total_money'],
                'accounting_date' => $billing_data['accounting_date']
            ];
            SumModel::create($sum_data);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            $transFlag = false;
            // 回滚事务
            Db::rollback();
        }
        if ($transFlag) {
            $this->success('操作成功');
        }
    }
    
    //历史水电
    public function history()
    {
        $number_id = $this->request->param('number_id/d', 0);
        $property_id = $this->request->param('property_id/d', 0);
        $tenant_id = $this->request->param('tenant_id/d', 0);
        $this->assign('number_id', $number_id);
        $this->assign('property_id', $property_id);
        $this->assign('tenant_id', $tenant_id);
        return $this->fetch();
    }

    //查看历史账单-table查询
    public function queryHistory()
    {
        $page = $this->request->param('page/d', LAYUI_PAGE);
        $limit = $this->request->param('limit/d', LAYUI_LIMIT);
        $number_id = $this->request->param('number_id/d', 0);
        $property_id = $this->request->param('property_id/d', 0);
        $tenant_id = $this->request->param('tenant_id/d', 0);
        $conditions = array(
            ['a.house_property_id', '=', $property_id],
            ['a.house_number_id', '=', $number_id],
            ['a.tenant_id', '=', $tenant_id],
            ['a.end_time', 'not null', '']
        );
        $count = BillingModel::where($conditions)->alias('a')->count();
        $billing_data = BillingModel::where($conditions)
        ->alias('a')
        ->join('HouseNumber b', 'b.id = a.house_number_id')
        ->join('HouseProperty c', 'c.id = a.house_property_id')
        ->field('a.*, b.name as number_name, c.name as property_name')
        ->order(['a.start_time' => 'desc'])
        ->page($page, $limit)
        ->select();
        return $this->returnLayui($billing_data, $count);
    }

    //新增账单
    public function bill()
    {
        $id = $this->request->param('id/d', 0);
        $house_property_id = $this->request->param('house_property_id/d', 0);
        $property_data = PropertyModel::get($house_property_id);
        $number_data = NumberModel::where('house_property_id', $house_property_id)
        ->where('rent_mark', 'Y')
        ->order('name')
        ->all();
        $data = [
            'id' => '',
            'house_property_id' => $house_property_id,
            'house_number_id' => '',
            'start_time' => \date('Y-m-d'),
            'other_charges' => '',
            'note' => '',
            'properyt_name' => $property_data->name
        ];
        if ($id) {
            if (!$data = BillingModel::get($id)) {
                $this->error('记录不存在。');
            }
            $data['properyt_name'] = $property_data->name;
            $number_name = NumberModel::where('id', $data['house_number_id'])->select()->toArray();
            $data['house_number_name'] = $number_name[0]['name'];
        }
        $this->assign('number_data', $number_data);
        $this->assign('data', $data);
        return $this->fetch();
    }

    //保存新账单
    public function saveBill()
    {
        $id = $this->request->post('id/d', 0);
        $data = [
            'house_property_id' => $this->request->post('house_property_id/d', 0),
            'house_number_id' => $this->request->post('house_number_id/d', 0),
            'start_time' => $this->request->post('start_time/s', \date('Y-m-d'), 'trim'),
            // 'end_time' => $this->request->post('start_time/s', \date('Y-m-d'), 'trim'),
            'other_charges' => $this->request->post('other_charges/d', 0),
            'total_money' => $this->request->post('other_charges/d', 0),
            'note' => $this->request->post('note/s', '', 'trim'),
        ];
        if ($id) {
            if (!$biling = BillingModel::get($id)) {
                $this->error('修改失败，记录不存在。');
            }
            $biling->save($data);
            $this->success('修改成功。');
        }
        $number_data = NumberModel::get($data['house_number_id']);
        $data['tenant_id'] = $number_data->tenant_id;
        BillingModel::create($data);
        $this->success('添加成功。');
    }

    //历史水电
    public function water()
    {
        $number_id = $this->request->param('number_id/d', 0);
        $property_id = $this->request->param('property_id/d', 0);
        $tenant_id = $this->request->param('tenant_id/d', 0);
        $this->assign('number_id', $number_id);
        $this->assign('property_id', $property_id);
        $this->assign('tenant_id', $tenant_id);
        return $this->fetch();
    }

    //收据页面-查询历史水电
    public function queryWater()
    {
        $number_id = $this->request->param('number_id/d', 0);
        $conditions = array(
            ['a.house_number_id', '=', $number_id],
            ['a.end_time', 'not null', '']
        );
        $billing_data = BillingModel::where($conditions)
        ->alias('a')
        ->join('HouseNumber b', 'b.id = a.house_number_id')
        ->join('HouseProperty c', 'c.id = a.house_property_id')
        ->field('a.*, b.name as number_name, c.name as property_name')
        ->order(['a.start_time' => 'desc'])
        ->limit(6)
        ->select();
        return $this->returnLayui($billing_data);
    }

    //集中抄水电表
    public function centralized()
    {
        $type = $this->request->param('type/s');
        $house_property_id = $this->request->param('house_property_id/d', 0);
        $property_data = PropertyModel::get($house_property_id);
        $conditions = array(
            ['a.house_property_id', '=', $house_property_id],
            ['a.start_time', '< time', 'today+10 days'],
            ['a.accounting_date', 'null', ''],
        );
        if ($type == 'e') {
            array_push($conditions, ['a.electricity_meter_this_month', 'null', '']);
        } elseif ($type == 'w') {
            array_push($conditions, ['a.water_meter_this_month', 'null', '']);
        }
        $data = BillingModel::where($conditions)
        ->alias('a')
        ->join('HouseNumber b', 'b.house_property_id = a.house_property_id and b.id = a.house_number_id')
        ->field('a.*, b.name')
        ->order('b.name')
        ->select();
        $this->assign('property_name', $property_data['name']);
        $this->assign('data', $data);
        $this->assign('house_property_id', $house_property_id);
        $this->assign('type', $type);
        return $this->fetch();
    }

    //保存集中抄表
    public function saveCentralized()
    {
        $data = $this->request->post('data');
        $house_property_id = $this->request->post('house_property_id/d', 0);
        $type = $this->request->post('type/s', 0);
        foreach ($data as $key => $value) {
            if ($value) {
                if (!$billing = BillingModel::get($key)) {
                    $this->error('修改失败，记录不存在');
                }
                $number_data = NumberModel::where('house_property_id', $billing->house_property_id)
                ->where('id', $billing->house_number_id)
                ->find();
                $data = array();
                $data['meter_reading_time'] = date('Y-m-d', time());
                if ($type == 'e') {
                    $data['electricity_meter_this_month'] = $value;
                    $data['electricity_consumption'] = $value - $billing['electricity_meter_last_month'];
                    $data['electricity'] = $data['electricity_consumption'] * $number_data->electricity_price;
                    $data['total_money'] = intval($billing['water'] + $data['electricity'] + $billing['rental']
                        + $billing['deposit'] + $billing['garbage_fee'] + $billing['other_charges']);
                    $billing->save($data);
                } elseif ($type == 'w') {
                    $data['water_meter_this_month'] = $value;
                    $data['water_consumption'] = $value - $billing['water_meter_last_month'];
                    $data['water'] = $data['water_consumption'] * $number_data->water_price;
                    $data['total_money'] = intval($data['water'] + $billing['electricity'] + $billing['rental']
                        + $billing['deposit'] + $billing['garbage_fee'] + $billing['other_charges']);
                    $billing->save($data);
                }
            }
        }
        $this->success('修改成功');
    }

    // 借贷平衡
    public function balance()
    {
        $id = $this->request->param('id/d', 0);
        if (!$billing_data = BillingModel::get($id)) {
            $this->error('记录不存在。');
        }
        $data_debit = [
            'house_property_id' => $billing_data['house_property_id'],
            'house_number_id' => $billing_data['house_number_id'],
            'start_time' =>  $billing_data['start_time'],
            'other_charges' => $billing_data['total_money'],
            'total_money' => $billing_data['total_money'],
            'note' => '借贷平衡',
        ];
        $data_crebit = [
            'house_property_id' => $billing_data['house_property_id'],
            'house_number_id' => $billing_data['house_number_id'],
            'start_time' =>  $billing_data['start_time'],
            'other_charges' => 0 - $billing_data['total_money'],
            'total_money' => 0 - $billing_data['total_money'],
            'note' => '借贷平衡',
        ];
        BillingModel::create($data_debit);
        BillingModel::create($data_crebit);
        $this->success('操作成功');
    }
}
